<template>
  <div class="fried-survey">
    <div class="header">
      <h1>{{ surveyConfig.title }}</h1>
      <p class="subtitle">{{ surveyConfig.subtitle }}</p>
      <div class="header-actions">
        <button @click="goToHome" class="home-btn">
          <span class="home-icon">🏠</span> {{ surveyConfig.buttons.home }}
        </button>
        <button @click="showSettings = true" class="settings-btn">
          <span class="settings-icon">⚙️</span> {{ surveyConfig.buttons.settings }}
        </button>
      </div>
    </div>

    <!-- 设置页面 -->
    <div class="settings-modal" v-if="showSettings">
      <div class="settings-content">
        <div class="settings-header">
          <h2>{{ surveyConfig.settings.title }}</h2>
          <button @click="closeSettings" class="close-btn">×</button>
        </div>

        <div class="settings-form">
          <div class="form-group">
            <label>问答编号：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.surveyId" placeholder="请输入问答编号（用于区分不同组的问卷）" maxlength="20">
            <p class="field-hint">编号用于区分不同组的问卷，建议使用如：GROUP001、BATCH_A等格式</p>
          </div>
          <div class="form-group">
            <label>记录人姓名：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.name" placeholder="请输入记录人姓名">
          </div>
          <div class="form-group">
            <label>记录人职务/身份：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.position" placeholder="请输入职务或身份（如：医生、护士、研究员等）">
          </div>
          <div class="form-group">
            <label>所属机构：</label>
            <input type="text" v-model="recorderInfo.institution" placeholder="请输入所属医院或机构名称">
          </div>
          <div class="form-group">
            <label>联系方式：</label>
            <input type="text" v-model="recorderInfo.contact" placeholder="请输入联系电话或邮箱">
          </div>
          <div class="form-group">
            <label>默认备注：</label>
            <textarea v-model="recorderInfo.defaultRemarks" placeholder="请输入默认备注信息（可选）" rows="3"></textarea>
          </div>
        </div>

        <div class="settings-actions">
          <button @click="saveRecorderInfo" class="save-settings-btn">保存设置</button>
          <button @click="closeSettings" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <!-- 记录人信息显示 -->
    <div class="recorder-info-display" v-if="recorderInfo.name && !showSettings && !showResult && !showExport">
      <div class="recorder-card">
        <div class="recorder-main-info">
          <h3>问答编号：{{ recorderInfo.surveyId }}</h3>
          <p>记录人：{{ recorderInfo.name }} | {{ recorderInfo.position }}</p>
          <p v-if="recorderInfo.institution">{{ recorderInfo.institution }}</p>
        </div>
        <div class="recorder-actions">
          <button @click="showSettings = true" class="edit-recorder-btn">编辑</button>
          <button @click="showExportDialog" class="export-btn">{{ surveyConfig.buttons.export }}</button>
        </div>
      </div>
    </div>

    <!-- 导出数据模态框 -->
    <div class="export-modal" v-if="showExport">
      <div class="export-content">
        <div class="export-header">
          <h2>{{ surveyConfig.export.title }}</h2>
          <button @click="closeExport" class="close-btn">×</button>
        </div>

        <div class="export-form">
          <div class="export-info">
            <p><strong>当前问答编号：</strong>{{ recorderInfo.surveyId }}</p>
            <p><strong>导出说明：</strong>将从服务器打包当前编号的所有问卷数据</p>
          </div>

          <div class="form-group">
            <label>导出密码：<span class="required">*</span></label>
            <input type="password" v-model="exportPassword" placeholder="请输入导出密码" @keyup.enter="exportData">
            <p class="field-hint">请联系管理员获取导出密码</p>
          </div>

          <div class="export-options">
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeRawData">
                包含原始评估数据
              </label>
            </div>
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeStatistics">
                包含统计分析
              </label>
            </div>
          </div>
        </div>

        <div class="export-actions">
          <button @click="exportData" class="export-confirm-btn" :disabled="!exportPassword">
            <span v-if="!isExporting">导出压缩包</span>
            <span v-else>导出中...</span>
          </button>
          <button @click="closeExport" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <div class="survey-form" v-if="!showResult && !showSettings && !showExport">
      <!-- 被评估人基本信息 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.basicInfo.title }}</h2>
        <div class="form-group" v-for="field in surveyConfig.sections.basicInfo.fields" :key="field.name">
          <label>{{ field.label }}：</label>
          <input 
            v-if="field.type === 'text' || field.type === 'number' || field.type === 'tel' || field.type === 'datetime-local'"
            :type="field.type" 
            v-model="formData[field.name]" 
            :placeholder="field.placeholder"
            :min="field.min"
            :max="field.max"
            :step="field.step"
            :rows="field.rows"
          >
          <textarea 
            v-else-if="field.type === 'textarea'"
            v-model="formData[field.name]" 
            :placeholder="field.placeholder"
            :rows="field.rows"
          ></textarea>
          <div v-else-if="field.type === 'radio'" class="radio-group">
            <label v-for="option in field.options" :key="option.value">
              <input type="radio" v-model="formData[field.name]" :value="option.value"> {{ option.label }}
            </label>
          </div>
        </div>
      </div>

      <!-- 问卷项目 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.assessment.title }}</h2>

        <div class="question-item" v-for="(question, index) in surveyConfig.sections.assessment.questions" :key="question.id">
          <h3>{{ index + 1 }}. {{ question.title }}</h3>
          <p class="question-desc">{{ question.description }}</p>
          
          <!-- 单选题 -->
          <div v-if="question.type === 'radio'" class="radio-group">
            <label v-for="option in question.options" :key="option.value">
              <input type="radio" v-model="formData[question.field]" :value="option.value"> {{ option.label }}
            </label>
          </div>
          
          <!-- 数字输入 -->
          <input 
            v-else-if="question.type === 'number'"
            type="number" 
            v-model.number="formData[question.field]" 
            :placeholder="question.placeholder"
            :step="question.step"
            :min="question.min"
            :max="question.max"
          >
          
          <!-- 提示信息 -->
          <p v-if="question.hint" class="hint">{{ question.hint }}</p>
          
          <!-- 子问题 -->
          <div v-if="question.subQuestions" class="sub-questions">
            <div v-for="subQ in question.subQuestions" :key="subQ.id" class="sub-question">
              <p><strong>{{ subQ.text }}</strong></p>
              <div class="radio-group">
                <label v-for="option in subQ.options" :key="option.value">
                  <input type="radio" v-model="formData[subQ.field]" :value="option.value"> {{ option.label }}
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="submit-section">
        <button @click="calculateResult" class="submit-btn" :disabled="!isFormValid">{{ surveyConfig.buttons.submit }}</button>
      </div>
    </div>

    <!-- 结果展示 -->
    <div class="result-section" v-if="showResult">
      <h2>{{ surveyConfig.result.title }}</h2>
      <div class="result-card">
        <div class="result-summary">
          <h3>{{ result.diagnosis }}</h3>
          <p class="score">{{ surveyConfig.result.totalScore }}：{{ result.totalScore }}/5</p>
        </div>

        <div class="result-details">
          <h4>{{ surveyConfig.result.details }}：</h4>
          <ul>
            <li v-for="(item, index) in result.details" :key="index" :class="item.positive ? 'positive' : 'negative'">
              {{ item.name }}：{{ item.result }} {{ item.positive ? '✓' : '✗' }}
            </li>
          </ul>
        </div>

        <div class="result-explanation">
          <h4>{{ surveyConfig.result.explanation.title }}：</h4>
          <p v-for="item in surveyConfig.result.explanation.items" :key="item">{{ item }}</p>
        </div>

        <div class="action-buttons">
          <button @click="saveToBackendOnly" class="save-btn" :disabled="isSaving">
            <span v-if="!isSaving">{{ surveyConfig.buttons.save }}</span>
            <span v-else>{{ surveyConfig.buttons.saving }}</span>
          </button>
          <button @click="resetForm" class="reset-btn">{{ surveyConfig.buttons.reset }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { surveyConfig } from '@/config/surveyConfig.js';
import { calculateAssessment, calculateStatistics, assessmentLogic } from '@/config/assessmentLogic.js';

export default {
  name: 'FriedSurvey',
  mounted() {
    // 自动设置当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

    // 加载记录人信息
    this.loadRecorderInfo();
  },
  data() {
    return {
      surveyConfig,
      showResult: false,
      showSettings: false,
      showExport: false,
      isExporting: false,
      isSaving: false,
      exportPassword: '',
      // 记录人信息（设置）
      recorderInfo: {
        surveyId: '',
        name: '',
        position: '',
        institution: '',
        contact: '',
        defaultRemarks: ''
      },
      // 导出选项
      exportOptions: surveyConfig.exportOptions,
      // 问卷表单数据
      formData: {
        // 被评估人信息
        patientName: '',
        age: null,
        gender: '',
        height: null,
        weight: null,
        phone: '',
        // 当前评估的记录时间和备注
        recordTime: '',
        remarks: '',
        // 评估项目
        weightLoss: '',
        walkTime: null,
        gripStrength: null,
        physicalActivity: null,
        fatigue1: '',
        fatigue2: ''
      },
      result: {
        totalScore: 0,
        diagnosis: '',
        details: []
      }
    }
  },
  computed: {
    isFormValid() {
      // 个人信息字段已改为选填，不再进行必填验证
      // 只检查记录人信息和评估项目的必填项
      return this.recorderInfo.surveyId &&
        this.recorderInfo.name &&
        this.recorderInfo.position &&
        this.formData.weightLoss &&
        this.formData.walkTime !== null &&
        this.formData.gripStrength !== null &&
        this.formData.physicalActivity !== null &&
        this.formData.fatigue1 !== '' &&
        this.formData.fatigue2 !== '';
    },
    bmi() {
      if (this.formData.height && this.formData.weight) {
        return this.formData.weight / Math.pow(this.formData.height / 100, 2);
      }
      return 0;
    }
  },
  methods: {
    // 导航方法
    goToHome() {
      this.$router.push('/');
    },

    // 设置相关方法
    saveRecorderInfo() {
      // 验证必填字段
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        alert('请填写所有必填信息（问答编号、记录人姓名、职务/身份）！');
        return;
      }

      // 保存记录人信息到本地存储
      localStorage.setItem('recorderInfo', JSON.stringify(this.recorderInfo));
      // 设置默认备注
      if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
        this.formData.remarks = this.recorderInfo.defaultRemarks;
      }
      this.showSettings = false;
      alert('记录人信息已保存！');
    },

    closeSettings() {
      this.showSettings = false;
    },

    loadRecorderInfo() {
      // 从本地存储加载记录人信息
      const saved = localStorage.getItem('recorderInfo');
      if (saved) {
        this.recorderInfo = JSON.parse(saved);
        // 设置默认备注
        if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
          this.formData.remarks = this.recorderInfo.defaultRemarks;
        }
      }
    },

    // 导出相关方法
    showExportDialog() {
      this.showExport = true;
      this.exportPassword = '';
    },

    closeExport() {
      this.showExport = false;
      this.exportPassword = '';
      this.isExporting = false;
    },


    getSurveysByGroup(surveyId) {
      // 从本地存储获取指定编号的所有问卷
      const allSurveys = JSON.parse(localStorage.getItem('surveyData') || '[]');
      return allSurveys.filter(survey => survey.surveyId === surveyId);
    },

    async exportData() {
      this.isExporting = true;

      try {
        // 发送导出请求到服务器
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/export-survey`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            surveyId: this.recorderInfo.surveyId,
            password: this.exportPassword,
            exportOptions: this.exportOptions
          })
        });

        if (response.status === 401) {
          alert('密码错误，请重新输入！');
          return;
        }

        if (!response.ok) {
          throw new Error('导出请求失败');
        }

        // 获取服务器返回的压缩包
        const blob = await response.blob();

        if (blob.size === 0) {
          alert('当前问答编号下没有问卷数据！');
          return;
        }

        // 下载服务器生成的压缩包
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `问卷数据_${this.recorderInfo.surveyId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        alert('数据导出成功！');
        this.closeExport();
      } catch (error) {
        console.error('导出失败:', error);
        alert('导出失败，请检查网络连接或联系管理员！');
      } finally {
        this.isExporting = false;
      }
    },

    generateExportContent(surveys) {
      const statistics = this.calculateStatistics(surveys);
      const summaryContent = assessmentLogic.generateSummaryReport(surveys, statistics, this.recorderInfo);
      
      // 生成详细数据
      const detailContent = assessmentLogic.generateDetailedCSV(surveys);

      return {
        summary: summaryContent,
        details: detailContent,
        surveys: surveys
      };
    },

    calculateStatistics(surveys) {
      return calculateStatistics(surveys);
    },

    async createAndDownloadZip(exportContent) {
      // 由于浏览器环境限制，这里模拟压缩包创建
      // 实际项目中应该使用JSZip库或发送到后台处理

      const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
      const filename = `问卷数据_${this.recorderInfo.surveyId}_${timestamp}`;

      // 创建汇总报告文件
      const summaryBlob = new Blob([exportContent.summary], { type: 'text/plain;charset=utf-8' });
      const summaryUrl = window.URL.createObjectURL(summaryBlob);
      const summaryLink = document.createElement('a');
      summaryLink.href = summaryUrl;
      summaryLink.download = `${filename}_汇总报告.txt`;
      document.body.appendChild(summaryLink);
      summaryLink.click();
      document.body.removeChild(summaryLink);
      window.URL.revokeObjectURL(summaryUrl);

      // 创建详细数据文件
      const detailBlob = new Blob([exportContent.details], { type: 'text/csv;charset=utf-8' });
      const detailUrl = window.URL.createObjectURL(detailBlob);
      const detailLink = document.createElement('a');
      detailLink.href = detailUrl;
      detailLink.download = `${filename}_详细数据.csv`;
      document.body.appendChild(detailLink);
      detailLink.click();
      document.body.removeChild(detailLink);
      window.URL.revokeObjectURL(detailUrl);

      // 如果包含原始数据，导出每份问卷的详细报告
      if (this.exportOptions.includeRawData && exportContent.surveys.length <= 10) {
        exportContent.surveys.forEach((survey, index) => {
          const reportContent = this.generateIndividualReport(survey);
          const reportBlob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' });
          const reportUrl = window.URL.createObjectURL(reportBlob);
          const reportLink = document.createElement('a');
          reportLink.href = reportUrl;
          reportLink.download = `${filename}_个人报告_${index + 1}_${survey.patientName}.txt`;
          document.body.appendChild(reportLink);
          reportLink.click();
          document.body.removeChild(reportLink);
          window.URL.revokeObjectURL(reportUrl);
        });
      }
    },

    formatTime(timeString) {
      if (!timeString) return '未知时间';
      try {
        const date = new Date(timeString);
        return date.toLocaleString('zh-CN');
      } catch (error) {
        return timeString;
      }
    },

    generateIndividualReport(survey) {
      return assessmentLogic.generateIndividualReport(survey, this.recorderInfo);
    },

    calculateResult() {
      // 使用配置文件中的评估逻辑
      this.result = calculateAssessment(this.formData);
      this.showResult = true;
    },

    async saveToBackendOnly() {
      this.isSaving = true;

      try {
        // 1. 保存问卷数据到后台
        await this.saveToBackend();

        // 2. 生成评估报告内容
        const timestamp = new Date().toLocaleString('zh-CN');
        const recordTime = this.formData.recordTime ?
          new Date(this.formData.recordTime).toLocaleString('zh-CN') :
          timestamp;

        const content = `Fried衰弱评估结果报告
问答编号：${this.recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${this.recorderInfo.name}
记录人职务/身份：${this.recorderInfo.position}
所属机构：${this.recorderInfo.institution}
联系方式：${this.recorderInfo.contact}
记录时间：${recordTime}
备注：${this.formData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${this.formData.patientName}
年龄：${this.formData.age}岁
性别：${this.formData.gender === 'male' ? '男性' : '女性'}
身高：${this.formData.height}cm
体重：${this.formData.weight}kg
BMI：${this.bmi.toFixed(1)}
联系电话：${this.formData.phone || '未填写'}

=== 评估结果 ===
总分：${this.result.totalScore}/5
诊断结果：${this.result.diagnosis}

=== 各项详细结果 ===
${this.result.details.map((item, index) =>
          `${index + 1}. ${item.name}：${item.result} ${item.positive ? '(阳性)' : '(阴性)'}`
        ).join('\n')}

=== 评分标准 ===
• 具备5条中3条及以上：衰弱综合征
• 不足3条：衰弱前期  
• 0条：无衰弱健康老人

=== 原始评估数据 ===
体重下降：${this.formData.weightLoss === 'yes' ? '是' : '否'}
行走时间：${this.formData.walkTime}秒
握力：${this.formData.gripStrength}kg
体力活动：${this.formData.physicalActivity}kcal/周
疲乏评分1：${this.formData.fatigue1}分
疲乏评分2：${this.formData.fatigue2}分

报告结束
`;

        // 3. 保存评估报告到@data/文件夹
        await this.saveFileToDataFolder(content);

        alert('✅ 数据已成功保存到后台！\n\n📁 问卷数据：survey_data/\n📄 评估报告：@data/');

      } catch (error) {
        console.error('保存到后台失败:', error);
        alert('❌ 保存失败，请检查网络连接或联系管理员！\n\n错误信息：' + error.message);
      } finally {
        this.isSaving = false;
      }
    },

    async saveFileToDataFolder(content) {
      // 通过API保存文件到@data/文件夹
      const filename = `Fried衰弱评估结果_${this.recorderInfo.surveyId}_${this.formData.patientName}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;

      const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-file`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          filename: filename,
          content: content,
          surveyId: this.recorderInfo.surveyId
        })
      });

      if (!response.ok) {
        throw new Error('保存文件失败');
      }

      const result = await response.json();
      console.log('文件已保存到:', result.filepath);
    },

    async saveToBackend() {
      // 构建要保存的数据
      const surveyData = {
        surveyId: this.recorderInfo.surveyId,
        recordTime: this.formData.recordTime,
        recorderName: this.recorderInfo.name,
        recorderPosition: this.recorderInfo.position,
        recorderInstitution: this.recorderInfo.institution,
        recorderContact: this.recorderInfo.contact,
        // 被评估人信息
        patientName: this.formData.patientName || "未填写",
        age: this.formData.age || 0,
        gender: this.formData.gender,
        height: this.formData.height,
        weight: this.formData.weight,
        phone: this.formData.phone,
        remarks: this.formData.remarks,
        // 评估数据
        weightLoss: this.formData.weightLoss === 'yes' ? 1 : 0,
        walkTime: this.formData.walkTime,
        gripStrength: this.formData.gripStrength,
        physicalActivity: this.formData.physicalActivity,
        fatigue1: this.formData.fatigue1,
        fatigue2: this.formData.fatigue2,
        // 评估结果
        totalScore: this.result.totalScore,
        diagnosis: this.result.diagnosis,
        // 时间戳
        createdAt: new Date().toISOString()
      };

      try {
        // 发送到后台API保存到工程文件夹
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-survey`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(surveyData)
        });

        if (response.ok) {
          console.log('问卷数据已保存到服务器文件夹');
        } else {
          throw new Error('保存失败');
        }
      } catch (error) {
        console.error('保存到服务器失败，使用本地存储备份:', error);
        // 如果服务器保存失败，使用本地存储作为备份
        const existingSurveys = JSON.parse(localStorage.getItem('surveyData') || '[]');
        existingSurveys.push(surveyData);
        localStorage.setItem('surveyData', JSON.stringify(existingSurveys));
      }
    },

    resetForm() {
      // 重置表单数据，但保留记录人信息
      this.formData = {
        // 被评估人信息
        patientName: '',
        age: null,
        gender: '',
        height: null,
        weight: null,
        phone: '',
        // 当前评估的记录时间和备注
        recordTime: '',
        remarks: this.recorderInfo.defaultRemarks || '',
        // 评估项目
        weightLoss: '',
        walkTime: null,
        gripStrength: null,
        physicalActivity: null,
        fatigue1: '',
        fatigue2: ''
      };

      // 重新设置当前时间
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

      this.result = {
        totalScore: 0,
        diagnosis: '',
        details: []
      };
      this.showResult = false;
    }
  }
}
</script>

<style scoped>
.fried-survey {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
}

.header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
}

.subtitle {
  margin: 0 0 15px 0;
  opacity: 0.9;
  font-size: 16px;
}

.header-actions {
  margin-top: 15px;
}

.home-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  margin-right: 10px;
}

.home-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
}

.home-icon {
  font-size: 16px;
}

.settings-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.settings-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
}

.settings-icon {
  font-size: 16px;
}

.section {
  background: white;
  border-radius: 10px;
  padding: 25px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border: 1px solid #e1e8ed;
}

.section h2 {
  color: #333;
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 22px;
  border-bottom: 2px solid #667eea;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

.form-group input[type="number"],
.form-group input[type="text"],
.form-group input[type="tel"],
.form-group input[type="datetime-local"],
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
  font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.radio-group {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.radio-group label {
  display: flex;
  align-items: center;
  font-weight: normal;
  cursor: pointer;
  margin-bottom: 0;
}

.radio-group input[type="radio"] {
  margin-right: 8px;
  transform: scale(1.2);
}

.question-item {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #667eea;
}

.question-item h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
  font-size: 18px;
}

.question-desc {
  margin-bottom: 15px;
  color: #666;
  line-height: 1.5;
}

.question-item input[type="number"] {
  max-width: 200px;
  padding: 10px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
}

.sub-question {
  margin: 20px 0;
  padding: 15px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e1e8ed;
}

.sub-question p {
  margin-bottom: 10px;
  color: #333;
}

.hint {
  font-size: 14px;
  color: #888;
  font-style: italic;
  margin-top: 8px;
}

.submit-section {
  text-align: center;
  margin-top: 30px;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 15px 40px;
  font-size: 18px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.result-section {
  background: white;
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.result-card {
  text-align: center;
}

.result-summary {
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
}

.result-summary h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.score {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

.result-details {
  text-align: left;
  margin-bottom: 25px;
}

.result-details h4 {
  color: #333;
  margin-bottom: 15px;
}

.result-details ul {
  list-style: none;
  padding: 0;
}

.result-details li {
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 6px;
  border-left: 4px solid #ddd;
}

.result-details li.positive {
  background: #f8d7da;
  border-left-color: #dc3545;
  color: #721c24;
}

.result-details li.negative {
  background: #d4edda;
  border-left-color: #28a745;
  color: #155724;
}

.result-explanation {
  text-align: left;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 25px;
}

.result-explanation h4 {
  margin-top: 0;
  color: #333;
}

.result-explanation p {
  margin: 8px 0;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.save-btn,
.reset-btn {
  padding: 12px 25px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.save-btn {
  background: #28a745;
  color: white;
}

.save-btn:hover:not(:disabled) {
  background: #218838;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
}

.save-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
  opacity: 0.7;
}

.reset-btn {
  background: #6c757d;
  color: white;
}

.reset-btn:hover {
  background: #5a6268;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(108, 117, 125, 0.3);
}

@media (max-width: 768px) {
  .fried-survey {
    padding: 10px;
  }

  .radio-group {
    flex-direction: column;
    gap: 10px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .save-btn,
  .reset-btn {
    width: 100%;
  }
}

/* 设置模态框样式 */
.settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.settings-content {
  background: white;
  border-radius: 15px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 30px 20px;
  border-bottom: 1px solid #e1e8ed;
}

.settings-header h2 {
  margin: 0;
  color: #333;
  font-size: 22px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 5px;
  border-radius: 50%;
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.settings-form {
  padding: 20px 30px;
}

.settings-actions {
  padding: 20px 30px;
  border-top: 1px solid #e1e8ed;
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.save-settings-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.save-settings-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.cancel-btn {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #ddd;
  padding: 12px 25px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

/* 记录人信息显示卡片 */
.recorder-info-display {
  margin-bottom: 20px;
}

.recorder-card {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
  padding: 20px;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(40, 167, 69, 0.2);
}

.recorder-main-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: bold;
}

.recorder-main-info p {
  margin: 0 0 5px 0;
  opacity: 0.9;
  font-size: 14px;
}

.recorder-actions {
  display: flex;
  gap: 10px;
}

.edit-recorder-btn,
.export-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.edit-recorder-btn:hover,
.export-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.export-btn {
  background: rgba(255, 193, 7, 0.3);
  border-color: rgba(255, 193, 7, 0.5);
}

.export-btn:hover {
  background: rgba(255, 193, 7, 0.5);
  border-color: rgba(255, 193, 7, 0.7);
}

/* 导出模态框样式 */
.export-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.export-content {
  background: white;
  border-radius: 15px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.export-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 30px 20px;
  border-bottom: 1px solid #e1e8ed;
}

.export-header h2 {
  margin: 0;
  color: #333;
  font-size: 22px;
}

.export-form {
  padding: 20px 30px;
}

.export-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #ffc107;
}

.export-info p {
  margin: 5px 0;
  color: #333;
}

.export-options {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.export-options .form-group {
  margin-bottom: 10px;
}

.export-options label {
  display: flex;
  align-items: center;
  font-weight: normal;
  cursor: pointer;
}

.export-options input[type="checkbox"] {
  margin-right: 8px;
  transform: scale(1.2);
}

.export-actions {
  padding: 20px 30px;
  border-top: 1px solid #e1e8ed;
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.export-confirm-btn {
  background: linear-gradient(135deg, #ffc107 0%, #ff8c00 100%);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.export-confirm-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(255, 193, 7, 0.4);
}

.export-confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.required {
  color: #dc3545;
  font-weight: bold;
}

.field-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  font-style: italic;
}

@media (max-width: 768px) {
  .settings-content {
    width: 95%;
    margin: 20px;
  }

  .settings-header,
  .settings-form,
  .settings-actions {
    padding-left: 20px;
    padding-right: 20px;
  }

  .recorder-card {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }

  .settings-actions {
    flex-direction: column;
  }

  .save-settings-btn,
  .cancel-btn {
    width: 100%;
  }
}
</style>
